package com.kjlink.internal.workreport.config.mybatis;

import cn.xuqiudong.common.base.model.BaseEntity;
import com.kjlink.internal.workreport.helper.SessionHelper;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import java.util.Properties;

/**
 * 描述: 在新增或修改的时候追加通用字段
 *
 * @author Vic.xu
 * @date 2022-03-02 9:29
 */
@Intercepts(@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}))
public class CommonFieldInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        fillCommonField(invocation);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 追加通用字段
     *
     * @param invocation
     */
    private void fillCommonField(Invocation invocation) {
        //Executor的update  方法有两个参数, 此处不再额外的判断
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        SqlCommandType sqlCommandType = ms.getSqlCommandType();
        Object parameter = args[1];

        switch (sqlCommandType) {
            case UPDATE:
                fillUpdateCommonField(parameter);
                break;
            case INSERT:
                fillInsertCommonField(parameter);
                break;
            default:
                break;
        }

    }

    private void fillInsertCommonField(Object parameter) {
        if (parameter instanceof BaseEntity) {
            BaseEntity model = (BaseEntity) parameter;

            Integer userId = SessionHelper.currentUserId();
            if (userId != null) {
                //没有手动设置的话：则设置创建人和修改人
                if (model.getCreateId() == null) {
                    model.setCreateId(userId);
                }
                if (model.getUpdateId() == null) {
                    model.setUpdateId(userId);
                }
            }


        }
    }

    private void fillUpdateCommonField(Object parameter) {
        if (parameter instanceof BaseEntity) {
            BaseEntity model = (BaseEntity) parameter;
            if (model.getVersion() != null) {
                model.setVersion(model.getVersion().intValue() + 1);
            }
            Integer userId = SessionHelper.currentUserId();
            if (userId != null) {
                //没有手动设置的话：则设置修改人
                if (model.getUpdateId() == null) {
                    model.setUpdateId(userId);
                }
            }
        }
    }
}